import java.io.IOException;
import java.io.PrintWriter;

import java.sql.ResultSet;
import java.sql.SQLException;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginHandler extends HttpServlet  {

	

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,
	IOException {
		
		res.setContentType("text/html");
		String username = req.getParameter("username");
		manageDbUser(username);
		
		HttpSession session = req.getSession();
		session.setAttribute("username", username);
		
		
	}

	public void manageDbUser(String username) {
		String query="SELECT id FROM users WHERE username ='"+username+"';";
		ResultSet result = PostgresDB.sendQuery(query);
		String val="";
	    try {
			while (result.next()) { // process results one row at a time
			    val = result.getString(1);	    
			  }
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if(val!=""){
			System.out.println("user found");
		}
		else{
			//add new user to database
			query="INSERT INTO users (username) VALUES ('"+username+"');";
			PostgresDB.sendQuery(query);
		}
	}


}


